//
//  SmartBandDelegateTool.m
//  UTEDemo
//
//  Created by VV on 2017/8/10.
//  Copyright © 2017年 vv. All rights reserved.
//

#import "SmartBandDelegateTool.h"
#import "MJExtension.h"
#import "YjHealthPlugin.h"
#import "YJUtils.h"
#import "YJDeviceManager.h"
@interface SmartBandDelegateTool ()

@property (nonatomic,strong) UTESmartBandClient         *smartBandMgr;
@property (nonatomic,assign) UTEPasswordType            passwordType;
@property (nonatomic,strong) UIAlertView                *alertView;
@property(nonatomic, assign) NSInteger userIDstatus;
@end

@implementation SmartBandDelegateTool

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.smartBandMgr = [UTESmartBandClient sharedInstance];
    }
    return self;
}

#pragma mark - UTEManagerDelegate
/// 发现设备
- (void)uteManagerDiscoverDevices:(UTEModelDevices *)modelDevices
{
    BOOL sameDevices = NO;
    for (UTEModelDevices *model in self.mArrayDevices) {
        if ([model.identifier isEqualToString:modelDevices.identifier]) {
            model.rssi = modelDevices.rssi;
            model.name = modelDevices.name;
            model.advertisementAddress = modelDevices.advertisementAddress;
            sameDevices = YES;
            break;
        }
    }
    
    if (!sameDevices) {
        NSLog(@"***Scanned device advertisementAddress=%@ name=%@ id=%@",modelDevices.advertisementAddress,modelDevices.name,modelDevices.identifier);
        [self.mArrayDevices addObject:modelDevices];
    }
    
    if (self.findDevicesBlock) {
        self.findDevicesBlock();
    }
}
/// callBack 反馈完成操作
- (void)uteManageUTEOptionCallBack:(UTECallBack)callback{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    switch (callback) {
        case UTECallBackDeviceBattery:
            [dic addEntriesFromDictionary:@{@"battery":@((long)self.smartBandMgr.connectedDevicesModel.battery)}];
            NSLog(@"此次demo读取的电量为%ld",(long)self.smartBandMgr.connectedDevicesModel.battery);
            break;
        default:
            break;
    }
    [[YjHealthPlugin sharedInstance] sendToFlutterName:yjUTECallBackTypeName tag:callback dict:dic];
}
/// 设备通讯方法
- (void)uteManagerDevicesSate:(UTEDevicesSate)devicesState error:(NSError *)error userInfo:(NSDictionary *)info
{
    if (error) {
        NSLog(@"***error code=%ld,msg=%@",(long)error.code,error.domain);
    }
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    
    switch (devicesState) {
        case UTEDevicesSateConnected: {
            //CN:每次连上应该设置一下配置，保证App和设备的信息统一
            //EN:You should set up the configuration every time you connect to ensure that the App and device information is unified
            //CN:关闭扫描
            //EN:Turn off scan
            [self.smartBandMgr stopScanDevices];
            //CN:设置设备时间
            //EN:Set device time
            [self.smartBandMgr setUTEOption:UTEOptionSyncTime];
            //CN:设置设备单位:公尺或者英寸
            //EN:Set device unit: meters or inches
        //    [self.smartBandMgr setUTEOption:UTEOptionUnitInch];
                [self.smartBandMgr setUTEOption:UTEOptionUnitMeter];
            /// 设置动态心率模式  设备心率自动检测，不支持切换
            [self.smartBandMgr setUTEOption:UTEOptionHeartSwitchDynamic];
            [self.smartBandMgr setUTEOption:UTEOptionReadBaseStatus];
            //CN:设置其他配置，防止手环被其他手机连接了，配置与现App不一致
            //EN:Set other configurations to prevent the bracelet from being connected by other phones, and the configuration is inconsistent with the current App
            UTEModelDevices *connectDevices = self.smartBandMgr.connectedDevicesModel;
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //CN:延迟一会儿，因为刚连接上，设备还在读取信息中
                //EN:Delay for a while, because the device is still reading the information just after connecting
                NSLog(@"***Device version=%@ Power=%ld rssi=%ld，address=%@",connectDevices.version,(long)connectDevices.battery, (long)connectDevices.rssi,connectDevices.address);
                /// 连接成功 传递给flutter  刷新UI
                NSMutableDictionary *dict = connectDevices.mj_keyValues;
                [dict removeObjectsForKeys:@[@"advertisementData", @"mServicesUUID", @"mServicesConnectedUUID", @"address"]];
                [[YjHealthPlugin sharedInstance] sendToFlutterName:yjSyncDataTypeName tag:devicesState dict:dict];
            });
            return;
        }
        case UTEDevicesSateDisconnected: {
            /// 断开连接 传递给flutter  刷新UI
            if (error) {
                NSLog(@"***Device disconnected abnormally=%@",error);
            }else {
                NSLog(@"***Device disconnected normally connectedDevicesModel=%@",self.smartBandMgr.connectedDevicesModel);
            }
            break;
        }
        case UTEDevicesSateSyncBegin: {
            NSLog(@"***Device synchronization starts");
            break;
        }
        case UTEDevicesSateSyncSuccess: {
            // 同步历史
            NSDictionary *dic = [self syncSucess:info];
            [dict addEntriesFromDictionary:dic];
            break;
        }
        case UTEDevicesSateSyncError: {
            break;
        }
        case UTEDevicesSateCheckFirmwareError: {
            break;
        }
        case UTEDevicesSateUpdateHaveNewVersion: {
//            if (self.connectVc.isMustUpdate) {
//                [self.smartBandMgr beginUpdateFirmware];
//            }
            break;
        }
        case UTEDevicesSateUpdateNoNewVersion: {
            break;
        }
        case UTEDevicesSateUpdateBegin: {
            break;
        }
        case UTEDevicesSateUpdateSuccess: {
            break;
        }
        case UTEDevicesSateUpdateError: {
            break;
        }
        case UTEDevicesSateHeartDetectingStart: {
            NSLog(@"***UTEOptionHeartDetectingStart -> Heart rate test started");
            break;
        }
        case UTEDevicesSateHeartDetectingStop: {
            NSLog(@"***UTEOptionHeartDetectingStop -> Heart rate test stopped");
            break;
        }
        case UTEDevicesSateHeartDetectingError: {
            NSLog(@"***The device disconnected during the heart rate test");
            break;
        }
        case UTEDevicesSateBloodDetectingStart: {
            NSLog(@"***Blood pressure test started");
            break;
        }
        case UTEDevicesSateBloodDetectingStop: {
            NSLog(@"***Blood pressure test stopped");
            break;
        }
        case UTEDevicesSateBloodDetectingError: {
            NSLog(@"***The device was disconnected during the blood pressure test");
            break;
        }
        case UTEDevicesSateStep: {
            NSLog(@"***Step status");
            break;
        }
        case UTEDevicesSateSleep: {
            NSLog(@"***Sleep state");
            break;
        }
        case UTEDevicesSatePasswordState:
        {
            NSLog(@"UTEDevicesSatePasswordState");
            NSString *value = info[kUTEPasswordState];
            switch (value.integerValue) {
                case UTEPasswordStateError:
                {
                    if (_passwordType == UTEPasswordTypeConnect) {
                        //Wrong password for connection
                        [self showPassAlertView:@"连接的密码错误，请重新输入"];
                    }else if (_passwordType == UTEPasswordTypeConfirm){
                        //The verified password is wrong
                        [self showPassAlertView:@"验证的密码错误，请重新输入"];
                    }
                    
                    break;
                }
                case UTEPasswordStateCorrect:
                {
                    if (_passwordType == UTEPasswordTypeConfirm) {
                        _passwordType = UTEPasswordTypeReset;
                        //Password verification is successful, please enter a new password
                        [self showPassAlertView:@"密码验证成功，请输入新的密码"];
                    }else if (_passwordType == UTEPasswordTypeReset){
                        NSLog(@"***The password is reset successfully, please remember the password");
                    }else{
                        NSLog(@"***The password is entered correctly and the bracelet starts to connect");
                    }
                    
                    break;
                }
                    
                case UTEPasswordStateNeed:
                {
                    _passwordType = UTEPasswordTypeConnect;
                    //To connect the bracelet, please enter the password
                    [self showPassAlertView:@"要连接手环，请输入密码"];
                    NSLog(@"请调用setUTEUserID 设置密码，如果密码与设备里面保存的不一致，设备界面会弹出连接确认对话框");
                    break;
                }
                case UTEPasswordStateNew:
                {
                    _passwordType = UTEPasswordTypeConnect;
                    //New bracelet, please enter a new password
                    [self showPassAlertView:@"新的手环，请输入新的密码"];
                    break;
                }
                    
            }
        }
        case UTEDevicesSateHeartCurrentValue:
        case UTEDevicesSateBodyTempNormal:
        case UTEDevicesSateHeartDetectingProcess:
        case UTEDevicesSateBloodDetectingProcess:
        case UTEDevicesSateBloodOxygenDetectingProcess:
        {
            // 实时采集
            NSDictionary *dic = [self syncCollectCurrent:info];
            [dict addEntriesFromDictionary:dic];
            break;
        }
            
            
        default: {
            break;
        }
    }
    ///  发送给flutter端
    [self sendToFlutterName:yjSyncDataTypeName tag:devicesState dict:dict];
}
/// 实时心率 最大值 最小值
- (void)uteManagerReceiveHRMMaxValue:(NSInteger)max minValue:(NSInteger)min averageValue:(NSInteger)average {
    NSLog(@"%ld", max);
    NSLog(@"%ld", min);
    NSLog(@"%ld", average);
}
/// 当 点击设备界面 【找手机】按钮，App的代理将接收到值
- (void)uteManageTouchDeviceReceiveData:(NSData *)data {
    Byte charFindPhone[2] = {0xd1,0x0a};
    NSData *dataFindPhone = [NSData dataWithBytes:charFindPhone length:2];
    
    Byte charMusicPlay[2] = {0xd1,0x07};
    NSData *dataMusicPlay = [NSData dataWithBytes:charMusicPlay length:2];
    
    Byte charMusicLast[2] = {0xd1,0x09};
    NSData *dataMusicLast = [NSData dataWithBytes:charMusicLast length:2];
    
    Byte charMusicNext[2] = {0xd1,0x08};
    NSData *dataMusicNext = [NSData dataWithBytes:charMusicNext length:2];
    
    //找手机
    if ([data isEqualToData:dataFindPhone]) {
        //点击了设备 「找手机」按钮
        NSDictionary *dic = @{};
        [[YjHealthPlugin sharedInstance] sendToFlutterName:yjCustomTypeName tag:yjCustomTypeFindPhone dict:dic];
    } else if ([data isEqualToData:dataMusicPlay]) {
        //点击了设备 播放音乐按钮
        NSDictionary *dic = @{};
        [[YjHealthPlugin sharedInstance] sendToFlutterName:yjCustomTypeName tag:yjCustomTypeMusicPlay dict:dic];
    } else if ([data isEqualToData:dataMusicLast]) {
        //点击了设备 音乐上一首按钮
        NSDictionary *dic = @{};
        [[YjHealthPlugin sharedInstance] sendToFlutterName:yjCustomTypeName tag:yjCustomTypeMusicLast dict:dic];
    } else if ([data isEqualToData:dataMusicNext]) {
        //点击了设备 音乐下一首按钮
        NSDictionary *dic = @{};
        [[YjHealthPlugin sharedInstance] sendToFlutterName:yjCustomTypeName tag:yjCustomTypeMusicNext dict:dic];
    }
}
- (void)uteManagerShortcutBtnStatus:(UTEDeviceShortcutBtnType)openType closeType:(UTEDeviceShortcutBtnType)closeType {
    NSLog(@"用户操作设备勿扰状态开关监听");
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"openType":@(openType),@"closeType":@(closeType)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerShortcutBtnStatus dict:dict];
}
/// 设置打开消息 可打电话 发信息
- (void)uteManagerExtraIsAble:(BOOL)isAble
{
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"isAble":@(isAble)};
    [dict addEntriesFromDictionary:dic];
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerExtraIsAble dict:dict];
}
- (void)uteManagerReceiveTodaySteps:(UTEModelRunData *)runData
{
    NSLog(@"***Today time=%@，Total steps=%ld,Total distance=%f,Total calories=%f,Current hour steps=%ld",runData.time,(long)runData.totalSteps,runData.distances,runData.calories,(long)runData.hourSteps);
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = runData.mj_keyValues;
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveTodaySteps dict:dict];
}
- (void)uteManagerReceiveTodaySport:(NSDictionary *)dict
{
    /*
    UTEModelSportWalkRun *walk = dict[kUTEQuerySportWalkRunData];
    NSLog(@"sport device step=%ld",(long)walk.stepsTotal);
    
    NSDictionary *dic = @{@"list" : @[walk.mj_keyValues]};
    [self sendToFlutterName:yjSyncData tag:UTESyncTypeStep dict:dic];
    */
    
}
- (void)uteManagerUTEIbeaconOption:(UTEIbeaconOption)option value:(NSString *)value
{
    NSLog(@"ibeacon value = %@",value);
}
- (void)uteManagerTakePicture
{
    NSLog(@"***I took a photo, if I don’t take a photo, please exit the photo mode");
}
- (void)uteManagerBluetoothState:(UTEBluetoothState)bluetoothState
{
    __weak typeof (self)weakSelf = self;
    if (bluetoothState == UTEBluetoothStateClose) {
        if (self.alertView) return;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            //Please turn on the phone Bluetooth
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请打开手机蓝牙" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil, nil];
            [alert show];
            weakSelf.alertView = alert;
        });
        
    }else{
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.alertView dismissWithClickedButtonIndex:0 animated:YES];
            weakSelf.alertView = nil;
            
            if (bluetoothState == UTEBluetoothStateOpen && ([YjHealthPlugin sharedInstance].identifier && [YjHealthPlugin sharedInstance].identifier.length > 0)) {
                /// 蓝牙开了 就去链接
                [[YJDeviceManager sharedInstance] connect];
            }
            
        });
    }
}
- (void)uteManagerReceiveCustomData:(NSData *)data result:(BOOL)result
{
    if (result) {
        NSLog(@"***Successfully received data = %@",data);
    }else{
        NSLog(@"***Failed to receive data");
    }
}
- (void)uteManagerSendCustomDataResult:(BOOL)result
{
    if (result) {
        NSLog(@"***Send custom data successfully");
    }else{
        NSLog(@"***Failed to send custom data");
    }
}
- (void)uteManagerUserIDStatus:(UTEUserIDStatus)status
{
    switch (status) {
        case UTEUserIDStatusRequired:
        {
            //发送UserID。 每次App连接设备，都需要设置User id
            //如果App设置的user id 与之前设备内保存的user id不一致，设备界面将会弹出窗口要求用户点击连接确认
            [self.smartBandMgr setUTEUserID:1234];
            break;
        }
        case UTEUserIDStatusOld:
        {
            //设备已经存在一个userid
            break;
        }
        case UTEUserIDStatusNew:
        {
            //设备不存在userid
            break;
        }
        case UTEUserIDStatusPaird:
        {
            //用户点击确定
            break;
        }
        case UTEUserIDStatusPairdCancel:
        {
            //用户点击取消
            break;
        }
        default:
            break;
    }
}
/**
 *  @discussion Monitor Device UTEDeviceSportMode status
 *  Required:isHasSportHRM=YES OR isHasSportPause=YES.
 *
 */
- (void)uteManagerReceiveSportMode:(UTEDeviceSportModeInfo *)info {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = info.mj_keyValues;
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveSportMode dict:dict];
}
/**
 *  @discussion It monitors the change of the device's sport data in real time, and it will be called frequently.
 *  Required:isHasSportHRM=Yes OR isHasHeadsetHRM=Yes .
 *
 *  @param dict key:kUTEQuerySportHRMData        value:UTEModelSportHRMData
 *         dict key:kUTEQuerySportHeadsetData    value:UTEModelSportHeadsetData
 */
- (void)uteManagerReceiveSportHRM:(NSDictionary *)dict {
    NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = dict;
    [d addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",d);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveSportHRM dict:d];
}
/**
 *  @discussion Progress of syncing data.
 *  @param process 0 to 100
 */
- (void)uteManagerSyncProcess:(NSInteger)process {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"process":@(process)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerSyncProcess dict:dict];
}
/**
 *  @discussion Progress of firmware upgrade.
 *
 *  @param process 0 to 100
 */
- (void)uteManagerUpdateProcess:(NSInteger)process {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"process":@(process)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerUpdateProcess dict:dict];
}
/**
 *  @discussion The device has exited camera mode
 *  Note:Only some devices support this method.
 */
- (void)uteManagerExitCameraMode {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerExitCameraMode dict:dict];
}
/**
 *  @discussion After querying by calling UTEOptionReadDisplaySize(setUTEOption:), this method callback.
 *
 *  @param width   Device screen resolution.
 *  @param height  Device screen resolution.
 *  @param count   Replaceable quantity.
 */
- (void)uteManagerDisplaySizeWidth:(NSInteger)width height:(NSInteger)height count:(NSInteger)count {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"width" : @(width), @"height" : @(height), @"count" : @(count)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerDisplaySizeWidth dict:dict];
}
/**
 *  @discussion Continue to send the remaining data
 *
 *  Note:When invoke sendUTECustomData:  to send data, if the data is too large,SDK will split the data and send it multiple times.
 *  Before each send, this proxy will be called to ask whether to continue sending.
 *
 *  Default yes if this proxy is not used.
 *
 */
- (BOOL)uteManagerSendCustomDataContinue {
    return YES;
}
/**
 *  @discussion     Sport status of Headset.
 *
 *  @param mode     See UTEDeviceSportMode
 *  @param open     Whether it is in sport model.
 *
 *  Note:If the state is open=NO, it means that the sport is stopped, and the mode is UTEDeviceSportModeNone.
 *
 *  @param support  Device support this sport type
 */
- (void)uteManagerHeadsetSport:(UTEDeviceSportMode)mode open:(BOOL)open suppport:(BOOL)support {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerHeadsetSport dict:dict];
}
/**
 *  @discussion What shortcut buttons the device supports.
 *  See method readDeviceShortcutBtnSupport
 *
 *  Note:Please use "bitwise AND" for value
 *  It is recommended to use uteManagerShortcutBtnSupportModel:
 */
- (void)uteManagerShortcutBtnSupport:(UTEDeviceShortcutBtnType)type {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"type":@(type)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerShortcutBtnSupport dict:dict];
}
/**
 *  @discussion What shortcut buttons the device supports.
 *  See method readDeviceShortcutBtnSupport
 */
- (void)uteManagerShortcutBtnSupportModel:(UTEModelShortcutBtn *)model {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = model.mj_keyValues;
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerShortcutBtnSupportModel dict:dict];
}
/**
 *  @discussion Status of device shortcut buttons.
 *  See method readDeviceShortcutBtnStatus
 */
- (void)uteManagerShortcutBtnStatusmModel:(UTEModelShortcutBtn *)model {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = model.mj_keyValues;
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerShortcutBtnStatusmModel dict:dict];
}
/**
 *  @discussion Heart rate data returned every ten minutes
 *
 *  @param dict key:kUTEQuery24HRMData value:UTEModelHRMData
 */
- (void)uteManagerReceiveTenMinLaterHRM:(NSDictionary *)dict {
    NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = dict;
    [d addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",d);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveTenMinLaterHRM dict:d];
}
/**
 *  @discussion Device debugging information.
 */
- (void)uteManagerReceiveDebugInfo:(NSDictionary *)dict {
    NSMutableDictionary *d = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = dict;
    [d addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",d);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveDebugInfo dict:d];
}
/**
 *  @discussion System Bluetooth notification permissions (share system notification permission status, not pairing status bound by the device).
 */
- (void)uteManagerANCSAuthorization:(BOOL)ancsAuthorized NS_AVAILABLE_IOS(13_0) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"ancsAuthorized":@(ancsAuthorized)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerANCSAuthorization dict:dict];
}
/**
 *  @discussion Received firmware UI version
 *  @param ver    version of the firmware e.g. @"U0008"
 */
- (void)uteManagerReceiveFirmwareUI:(NSString *)ver {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"ver":ver};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveFirmwareUI dict:dict];
}
/**
 *  @discussion Received Device Bluetooth3.0 info
 *  @param model  See UTEModelBluetooth3_0
 *
 *  Required: isHasBluetooth3=YES.
 */
- (void)uteManagerReceiveBluetooth3Info:(UTEModelBluetooth3_0 *)model {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = model.mj_keyValues;
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveBluetooth3Info dict:dict];
}
/**
 *  @discussion Device changed alarm clock(Add or delete on the device interface)
 *  @param array If is nil, Indicates that the device does not have alarm clock.
 *  @param success The data is complete and there is no loss.
 *
 *  Required: isHasClockTitle=YES.
 */
- (void)uteManagerReceiveAlarmChange:(NSArray<UTEModelAlarm *> *)array success:(BOOL)success {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerReceiveAlarmChange dict:dict];
}
- (void)uteManagerFactoryTestButtonCallback:(NSInteger)totalButton currentBtnIndex:(NSInteger)index {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"totalButton":@(totalButton),@"index":@(index)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerFactoryTestButtonCallback dict:dict];
}
- (void)uteManagerFactoryTestTpCallback:(NSInteger)position {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"position":@(position)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerFactoryTestTpCallback dict:dict];
}
- (void)uteManagerFactoryTestRGBCallback:(BOOL)open {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{@"open":@(open)};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerFactoryTestRGBCallback dict:dict];
}
- (void)uteManagerFactoryTestLogData:(NSData *)data strData:(NSString *)strData tag:(NSInteger)tag {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:@{@"methods" : [NSString stringWithFormat:@"%s",__FUNCTION__]}];
    NSDictionary *dic = @{};
    [dict addEntriesFromDictionary:dic];
    NSLog(@"##############################");
    NSLog(@"##############################");
    NSLog(@">>>>>>>>>>>>>>>>%@<<<<<<<<<<<<",dict);
    NSLog(@"##############################");
    NSLog(@"##############################");
    [self sendToFlutterName:yjSDKDelegateTypeName tag:yjSDKDelegateTypeUteManagerFactoryTestLogData dict:dict];
}
#pragma mark - 私有方法
/// 发送给flutter
- (void)sendToFlutterName:(NSString *)name tag:(NSInteger)tag dict:(NSDictionary *)dict {
    [[YjHealthPlugin sharedInstance] sendToFlutterName:name tag:tag dict:dict];
}
/// 实时采集
- (NSDictionary *)syncCollectCurrent:(NSDictionary *)info
{
    NSArray *firstArrayKeys = info.allKeys;
    NSArray *firstArrayValues = info.allValues;
    NSMutableArray *data = [[NSMutableArray alloc] init];
    for (int i = 0; i < firstArrayValues.count; i++) {
        NSString *key = firstArrayKeys[i];
        NSObject *value = firstArrayValues[i];
        NSMutableArray *d = [[NSMutableArray alloc] init];
        
        if ([value isKindOfClass:[NSArray class]]) {
            // 如果子元素还是数组  再遍历model
            for (NSObject *m in (NSArray *)value) {
                NSDictionary *dict = m.mj_keyValues;
                [d addObject:dict];
            }
        } else {
            NSDictionary *dict = value.mj_keyValues;
            [d addObject:dict];
        }

        NSDictionary *dic = @{key : d};
        [data addObject:dic];
    }
    NSDictionary *ddd = @{@"list" : data};
    return ddd;
}
///  同步历史数据
- (NSDictionary *)syncSucess:(NSDictionary *)info
{
    NSLog(@"Synchronization complete");
    NSArray *firstArrayKeys = info.allKeys;
    NSArray *firstArrayValues = info.allValues;
    NSMutableArray *data = [[NSMutableArray alloc] init];
    for (int i = 0; i < firstArrayValues.count; i++) {
        NSArray *arrayKey = firstArrayKeys[i];
        NSArray *arrayValue = firstArrayValues[i];
        NSMutableArray *d = [[NSMutableArray alloc] init];
        for (NSObject *model in arrayValue) {
            if ([model isKindOfClass:[NSArray class]]) {
                // 如果子元素还是数组  再遍历model
                for (NSObject *m in (NSArray *)model) {
                    NSDictionary *dict = m.mj_keyValues;
                    [d addObject:dict];
                }
            } else {
                NSDictionary *dict = model.mj_keyValues;
                [d addObject:dict];
            }
        }
        NSDictionary *dic = @{arrayKey : d};
        [data addObject:dic];
    }
    NSDictionary *ddd = @{@"list" : data};
    return ddd;
}
- (void)showPassAlertView:(NSString *)str
{
    UIAlertView *passView = [[UIAlertView alloc] initWithTitle:str
                                                       message:nil
                                                      delegate:self
                                             cancelButtonTitle:@"取消"
                                             otherButtonTitles:@"确定", nil];
    [passView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *txtName = [passView textFieldAtIndex:0];
    txtName.keyboardType = UIKeyboardTypeNumberPad;
    txtName.placeholder = @"请输入";
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [passView show];
    });
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        UITextField *txt = [alertView textFieldAtIndex:0];
        [self.smartBandMgr sendUTEPassword:txt.text type:_passwordType];
    }
}

- (void)onClickModifyPassword
{
    [self showPassAlertView:@"请输入密码验证"];
    _passwordType = UTEPasswordTypeConfirm;
}

- (NSMutableArray *)mArrayDevices
{
    if (!_mArrayDevices) {
        self.mArrayDevices = [NSMutableArray array];
    }
    return _mArrayDevices;
}
@end
